/*                                    _
 *   ___ _ __ ___ _ __ ___   ___   __| |
 *  / __| '__/ __| '_ ` _ \ / _ \ / _` |
 *  \__ \ |  \__ \ | | | | | (_) | (_| |
 *  |___/_|  |___/_| |_| |_|\___/ \__,_|                                  
 *
 *	 __|_ _ _|_ _   |_  _ | _  _  _ _ 
 *	_\ | (_| | (/_  | |(/_||_)(/_| _\  
 *                         |                             
 *	        _ _  _  _|   | _ 
 *         | | |(_)(_||_||(/_
 */

#define MODULE_NAME "StateHelpers"

#include "srs.statehelpers\debug.sp"
#include "srs.statehelpers\survivorindex.sp"
#include "srs.statehelpers\versioning.sp"
#include "srs.statehelpers\roundstatus.sp"
#include "srs.statehelpers\gamemodestatus.sp"

static const		MAX_TEMP_HEALTH						= 99;
static const String:CVAR_TEMP_HEALTH_DECAY[]			= "pain_pills_decay_rate";
static const String:ENTPROP_TEMP_HEALTH[]				= "m_healthBuffer";
static const String:ENTPROP_TEMP_HEALTH_DECAY[]			= "m_healthBufferTime";
static 		 Handle:cvarTempHealthDecay					= INVALID_HANDLE;

static bool:InPluginEnd = false;

StateHelpers_OnPluginStart()
{
	Debug_OnPluginStart();
	SurvivorIndex_OnPluginStart();
	RoundCounter_OnPluginStart();
	GameModeStatus_OnPluginStart();
	
	cvarTempHealthDecay =	FindConVar(CVAR_TEMP_HEALTH_DECAY);
}

stock L4D2_GetSurvivorAbsHealth(client)
{
	return (L4D2_GetAccurateTempHealth(client) + L4D2_GetEntityHealth(client));
}

stock L4D2_GetAccurateTempHealth(client)
{
	new value = RoundToCeil(GetEntPropFloat(client, Prop_Send, ENTPROP_TEMP_HEALTH) - ((GetGameTime() - GetEntPropFloat(client, Prop_Send, ENTPROP_TEMP_HEALTH_DECAY)) * GetConVarFloat(cvarTempHealthDecay))) - 1;
	
	if (value > MAX_TEMP_HEALTH)
	{
		value = RoundToCeil(GetEntPropFloat(client, Prop_Send, ENTPROP_TEMP_HEALTH));
		
		if (value > MAX_TEMP_HEALTH)
		{
			Debug_Print("GetAccurateTempHealth bug: Temp Health beyond all limits: %i", value);
			value = 0;
		}
	}
	
	return (value > 0) ? value : 0;
}

StateHelpers_OnPluginEnd()
{
	InPluginEnd = true;
}

stock bool:IsPluginEnding()
{
	return InPluginEnd;
}

StateHelpers_OnMapStart()
{
	RoundCounter_OnMapStart();
	SurvivorIndex_OnMapStart();
}

StateHelpers_OnMapEnd()
{
	RoundCounter_OnMapEnd();
	SurvivorIndex_OnMapEnd();
}

#undef MODULE_NAME